package ws

import (
	"encoding/json"
	"fmt"
	"github.com/gogf/gf/encoding/gjson"
	"github.com/gogf/gf/util/gconv"
	"live/libaray/tools"

	"github.com/go-redis/redis"
	"github.com/gogf/gf/database/gredis"
	"github.com/gogf/gf/frame/g"
)

var (
	redisCli          *redis.Client
	queueMsg          = g.Cfg().GetString("queue.Message")
	queueSysBroadcast = g.Cfg().GetString("queue.SysBroadcast")
)

func init() {
	_ = gredis.SetConfigByStr(g.Cfg().GetString("redis.default"))
	conf, ok := gredis.GetConfig()
	if !ok {
		g.Log().Panic("redis配置读取失败")
	}
	redisCli = redis.NewClient(&redis.Options{
		Addr:     fmt.Sprintf("%s:%d", conf.Host, conf.Port),
		Password: conf.Pass,
		DB:       conf.Db,
	})
	if pong, err := redisCli.Ping().Result(); err != nil {
		g.Log().Warningf("RedisClient Ping Result pong: %s,  err: %s", pong, err)
	}

	// 注册处理ws系统广播消息的方法
	RegisterSysBroadcast("online", OnSysBroadOnline)
}

// 订阅消息通道
func Subscribe() {
	// 订阅消息队列
	go subMsgQueue()
	// 订阅系统广播
	go subSysBroadcast()
}

// 订阅消息队列
func subMsgQueue() {
	ch := redisCli.Subscribe(queueMsg).Channel()
	for {
		msg, ok := <-ch
		if !ok {
			g.Log().Debugf("queue.Message Channel !ok: %v", ok)
			tools.MessageLog("queue.Message Channel !ok: %v" + gconv.String(ok))
			break
		}
		obj := &MessagePush{}
		err := json.Unmarshal([]byte(msg.Payload), obj)
		if err != nil {
			tools.MessageLog("数据解析错误：" + err.Error())
		}
		jsonStr, _ := gjson.New(obj).ToJsonString()
		tools.MessageLog("解析前：" + msg.Payload)
		tools.MessageLog("解析后：" + jsonStr)
		g.TryCatch(func() {
			RunMessagePush(obj)
		}, func(exception interface{}) {
			tools.MessageLog("推送消息异常：" + gconv.String(exception))
		})

	}
}

// 订阅系统广播
func subSysBroadcast() {
	tools.MessageLog("订阅系统广播")
	ch := redisCli.Subscribe(queueSysBroadcast).Channel()
	for {
		msg, ok := <-ch
		if !ok {
			g.Log().Debugf("queue.SysBroadcast Channel !ok: %v", ok)
			break
		}
		obj := &SysBroadcast{}
		err := json.Unmarshal([]byte(msg.Payload), obj)
		if err != nil {
			tools.MessageLog("订阅系统广播 数据解析错误:" + err.Error())
		}
		RunSysBroad(obj)
	}
}
